package com.robot.io;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class WriteInFile {

	private String fileName;
	private String folderName;
	private File textFile;
	private String extension;

	public WriteInFile(String folder, String fileName, String extension) {
		this.fileName=fileName;
		this.folderName=folder;
		this.extension=extension;
		textFile = new File(folder+"/"+fileName+"."+extension);
	}

	private void deleteFile(){
		if (textFile.exists())
				textFile.delete();
	}
	
	public void initializeFile(){		
		try {
			this.deleteFile();
			textFile.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void writeTextFile(String stringToWrite) {
		FileWriter fileWriter = null;
		BufferedWriter bufferedWriter = null;
		try {
			if (!textFile.exists()){
				System.out.println("File doesnt exist. Is being created");
				textFile.createNewFile();
			} else {
				fileWriter = new FileWriter(textFile.getCanonicalPath(), true);
				
				bufferedWriter = new BufferedWriter(fileWriter);
			    bufferedWriter.write(stringToWrite);
			    bufferedWriter.newLine();
			    bufferedWriter.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fileWriter != null) {
				try {
					fileWriter.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	} 
}
